// pages/main/main.js
const app = getApp();
//var index1=1;
Page({

    /**
     * 页面的初始数据
     */
    data: {
        num: [],
        userInfo: {},
        bususer: {},
        dataFlag:0,
        array: [],
        array1: ['全部', '未学','已学'],
        index: 11,//月份
        index1: 1,//状态：已学，未学
        scrollheight: 300,
        list:[],
        list1:[],
        currentIndex: 0,
        isloading: false,
        pagesize: 10,
        useropenid:null
    },
    genDateArray: function () {
        var thisYear = new Date().getFullYear();
        var startYear = thisYear - 2;
        var thisMonth = new Date().getMonth() + 1;
        var result = [];
        for (var i = startYear; i <= thisYear; i++) {
            var preStr = i + "";
            for (var j = 1; (i < thisYear && j <= 12) || (i == thisYear && j <= thisMonth); j++) {
                if (j < 10) {
                    j = "0" + j;
                }
                result.push(preStr + "-" + j + "");
            }
        }
        console.log(result);
        return result;
    },
    bindDateChange: function (e) {
        this.setData({
            date: e.detail.value
        })
    },
    /*按年月获取已学习人数/总人数*/
    loadstudydata: function (time, callback) {
        wx.showLoading({
            title: '加载数据...',
        })

        var that = this
        wx.request({
            method: 'GET',
            url: app.globalData.serverPath + "api/bs-mass-statistics-by-yyyy-mm",
            header: {
                'Authorization': app.globalData.token
            },
            data: {
                yyyy_MM:time
            },
            success: function (res) {
                console.log(res)
                that.setData({ num: res.data});
                if (callback) {
                    callback(res.data);
                }
            },
            complete: function () {
                wx.hideLoading();
            }
        })
    },
    /**加载驾驶员数据 */
    loaddriverdata: function(status,callback){
        if (this.data.isloading) {
            return;
        }
        wx.showLoading({
            title: '加载数据...',
        })

        var that=this
        wx.request({
            method: 'GET',
            url: app.globalData.serverPath + "api/get-bs-mass-centers-list",
            header: {
                'Authorization': app.globalData.token
            },
            data: {
                isLess: status,
                page: this.data.currentIndex,
                size: this.data.pagesize
            },
            success: function (res) {
                console.log(res)
                that.setData({
                    dataFlag:status
                })
                if(res.data.content &&res.data.content.length>0){
                    for(var i=0;i<res.data.content.length;i++){
                        res.data.content[i].sendTime = res.data.content[i].sendTime.split("-")[0] + "/" + res.data.content[i].sendTime.split("-")[1]
                    }
                }
                that.setData({ list: that.data.list.concat(res.data.content)});
                that.setData({ currentIndex: res.data.number});
                if (res.data.last) {//最后一页，停止所有加载
                    that.setData({ isloading: true });
                } else {
                    that.setData({ isloading: false });
                }
                if(callback){
                    callback(res.data);
                }
            },
            complete:function(){
                wx.hideLoading();
            }
        })
    },

    /**加载安全员列表 */
    loadsafedata:function(time,status,callback){
        if(this.data.isloading){
            return;
        }
        this.setData({ isloading: true });
        wx.showLoading({
            title: '加载数据...',
        })
        var lessType=0;
        if(status==0){
            lessType=-1
        }else if(status==2){
            lessType = 3
        }
        var that = this
        wx.request({
            method: 'GET',
            url: app.globalData.serverPath + "api/bs-mass-center-send-users-less-type",
            header: {
                'Authorization': app.globalData.token
            },
            data: {
                lessType: lessType,
                yyyy_MM: time,
                page: this.data.currentIndex,
                size:this.data.pagesize
            },
            success: function (res) {
                console.log(res)
                that.setData({ list1: that.data.list1.concat(res.data.content) });
                that.setData({ currentIndex: res.data.number});
                if (res.data.last) {//最后一页，停止所有加载
                    that.setData({ isloading: true });
                } else {
                    that.setData({ isloading: false });
                }

                if (callback) {
                    callback(res.data);
                }
            },
            complete: function(){
                wx.hideLoading()
            }
        })
    },

    /**安全员滚动翻页 */
    nextpage: function () {
        console.log("bottom");
        this.setData({
            currentIndex: this.data.currentIndex + 1
        });
        var tab = this.data.index1;
        this.loadsafedata(this.data.array[this.data.index], this.data.index1)
    },


    bindPickerChange: function (e) {
        this.setData({
            index: e.detail.value,
            isloading: false,
            currentIndex: 0,
            list1: []
        });
        this.loadstudydata(this.data.array[this.data.index])
        this.loadsafedata(this.data.array[this.data.index], this.data.index1)
    },
    bindPickerChange1: function (e){
        this.setData({
            index1: e.detail.value,
            isloading: false,
            currentIndex: 0,
            list1: []
        });
        this.loadsafedata(this.data.array[this.data.index],this.data.index1)
    },

    gotostudyinfo: function (e) {
        var id = e.currentTarget.dataset.id;
        var sid = e.currentTarget.dataset.sid;
        wx.navigateTo({
            url: '../studyinfo/studyinfo?id=' + id + '&sid=' + sid
        });
    },

    makecall: function (e) {
        var phone = e.currentTarget.dataset.phone;
        if (phone && phone.length > 0) {
            wx.makePhoneCall({
                phoneNumber: phone
            })
        }
    },

    /**驾驶员滚动翻页 */
    drivernextpage: function () {
        console.log("bottom");
        this.setData({
            currentIndex: this.data.currentIndex + 1
        });
        this.loaddriverdata(this.data.dataFlag);
    },

    /**驾驶员功能，切换未学习，已学习 */
    studyTabClick:function(e){
        var dataflag=e.currentTarget.dataset.flag;
        this.setData({ dataFlag: dataflag });
        this.refreshData();
    },

    refreshData:function(){
        if (!this.data.bususer) return;
        //司机
        if (this.data.bususer.userType == 2 || this.data.bususer.userType == '2') {
            this.setData({
                isloading: false,
                currentIndex: 0,
                list: []
            });
            this.loaddriverdata(this.data.dataFlag);
        } else {//安全员
            this.setData({
                isloading: false,
                currentIndex: 0,
                list1: []
            });
            this.loadsafedata(this.data.array[this.data.index], this.data.index1);
            this.loadstudydata(this.data.array[this.data.index])
        }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
      var that=this;
        this.setData({
            scrollheight: app.globalData.windowHeight * 0.89,
            array: this.genDateArray()
        });
        this.setData({
            index: this.data.array.length - 1
        })
        if(app.globalData.loginfinish){
          if (app.globalData.bususer) {
            this.setData({
              bususer: app.globalData.bususer
            })
            if (app.globalData.userInfo) {
              this.setData({
                userInfo: app.globalData.userInfo,
                hasUserInfo: true
              })
            }
            this.refreshData();
          } 
        }else{
          wx.showLoading({
            title: '登录中...',
          })
          app.initApp(function(res){
            app.processLogin(app.globalData.loginresult,function(){
              wx.hideLoading();
              if (app.globalData.bususer) {
                that.setData({
                  bususer: app.globalData.bususer
                })
                if (app.globalData.userInfo) {
                  that.setData({
                    userInfo: app.globalData.userInfo,
                    hasUserInfo: true
                  })
                }
              }
              that.refreshData();
            });
          });
        }
        
        

    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        console.log("onShow")
        var that=this;
        this.setData({
          bususer: app.globalData.bususer
        });
        if (app.globalData.openid) {
          this.setData({
            useropenid: app.globalData.openid
          })
        }
        app.validateopenid(function(){
          if (app.globalData.loginfinish) {
            if (app.globalData.token && app.globalData.token.length > 0) {
              console.log("app.globalData.token>>", app.globalData.token);
              that.refreshData();
            }
          }
        });  
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function (e) {
        console.log("onPullDownRefresh");
        if (app.globalData.token && app.globalData.token.length > 0) {
            this.loaddriverdata(this.data.dataFlag, function (res) {
                wx.stopPullDownRefresh();
            });
        }
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    },

    kindToggle: function (e) {
        var id = e.currentTarget.id

            , list = this.data.list;
        for (var i = 0, len = list.length; i < len; ++i) {
            if (list[i].id == id) {
                list[i].open = !list[i].open
            } else {
                list[i].open = false
            }
        }
        this.setData({
            list: list
        });
    }
})